<template>
  <Card>
    <Api ref="apiRef" :immediate="false" :load="() => listAppsByProjectId(project?.id)" type="Array">
      <Space direction="vertical">
        <ProjectTab @change="onChangeProject" />
        <Space>
          <Button shape="circle" type="primary" @click="onCreate({ projectId: project.id })" :disabled="!project?.id">
            <IconPlus />
          </Button>
        </Space>
        <Table>
          <TableColumn title="全称" field="name">
            <template #cell="{ row }">
              <Popover position="right">
                <Button isText :text="row.name" />
                <template #content>
                  <Space>
                    <Button text="编辑" @click="onCreate(row)" />
                    <Button text="删除" @click="onDelete(row.id)" />
                  </Space>
                </template>
              </Popover>
            </template>
          </TableColumn>
          <TableColumn title="简称" field="shortName" />
          <TableColumn title="Key" field="key" />
          <TableColumn title="前端地址" field="frontUrl" />
          <TableColumn title="后端地址" field="backUrl" />
          <TableColumn title="备注" field="remark" />
          <TableColumn title="创建日期" :width="120" field="createdAt" type="Date" />
          <TableColumn title="更新日期" :width="120" field="updatedAt" type="Date" />
        </Table>
      </Space>
    </Api>
  </Card>
</template>

<script setup lang="ts">
import { Api } from '@idmy/core'
import { Button, Card, Popover, Space, Table, TableColumn } from '@idmy/ui'
import { IconPlus } from '@idmy/ui-icon'
import { deleteApp, listAppsByProjectId } from './services'
import ProjectTab from '@/components/sys/Project/tab/index.vue'
import AppCreate from '@/components/sys/App/create/index.vue'

const apiRef = ref()
const load = () => apiRef.value.onLoad()

const project = ref()
const onChangeProject = val => {
  project.value = val
  load()
}

const onCreate = model =>
  Modal.open({
    component: AppCreate,
    title: model.id ? '更新应用' : '创建应用',
    enableLock: true,
    props: {
      model,
    },
    onClose: isOk => isOk && load(),
  })

const onDelete = useDelete(deleteApp, load)
</script>
